import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/login',
    name: '登录',
    meta: {
      title: '登录'
    },
    component: () => import('../views/Login'),
    // 独享守卫
    beforeEnter: (to, from, next) => {
      if (getToken()?.length > 0) {
        // next(false)
        // 返回首页
        next('/layout/home')
      } else {
        next()
      }
    }
  },
  {
    path: '/layout',
    meta: {
      title: '首页'
    },
    redirect: '/layout/home',
    component: () => import('../views/Layout'),
    children: [
      {
        path: 'home',
        name: 'home',
        meta: {
          title: '主页',
          scrollT: 0 // 滚动条位置
        },
        component: () => import('../views/Home')
      },
      {
        path: 'user',
        name: 'user',
        meta: {
          title: '我的'
        },
        component: () => import('../views/User')
      }
    ]
  },
  {
    path: '/search',
    name: 'search',
    meta: {
      title: '搜索'
    },
    component: () => import('../views/Search')
  },
  {
    path: '/search/:q',
    name: 'search-result',
    meta: {
      title: '搜索结果'
    },
    component: () => import('../views/Search/SearchResult'),
    props: true
  },
  {
    path: '/article-detail',
    name: 'article-detail',
    meta: {
      title: '文章详情'
    },
    component: () => import('../views/ArticleDetail')
  },
  {
    path: '/user-edit',
    name: 'user-edit',
    meta: {
      title: '编辑资料'
    },
    component: () => import('../views/User/UserEdit')
  },
  {
    path: '/chat',
    name: 'chat',
    meta: {
      title: '聊天页面'
    },
    component: () => import('../views/Chat')
  }

]

const router = new VueRouter({
  routes
})

// 1.前置路由守卫
// router.beforeEach((to, from, next) => {
//   if (getToken()?.length > 0 && to.path === '/login') {
//     // next('/layout/home')
//     // 返回首页
//     next('/layout/home')
//   } else {
//     next()
//   }
// })

// 2.后置路由守卫
router.afterEach((to, from) => {
  document.title = to.meta.title
})

export default router
